package com.hejia.bulbul.controller;

import com.hejia.alauda.utils.ControllerHelper;
import com.upyun.*;
import com.upyun.UpYun.FolderItem;
import com.upyun.api.utils.UpYunException;
import com.upyun.api.utils.UpYunUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/upyun")
public class UpYunController extends BaseController {

	@Resource(name = "upYunUploader")
	private UpYunUploader uploader;

    @Resource(name = "upYunUploaderFile")
    private UpYunUploader uploaderFile;

	@Resource
	private UpYun upYun;

	@RequestMapping(value = "upload", method = RequestMethod.GET)
	@ResponseBody
	public UpYunEntity up(HttpServletRequest request,String upYunSaveFolder) throws UpYunException {
		long expiration = System.currentTimeMillis() / 1000 + 6 * 10 * 30; // 以秒为单位，过期时间默认30分钟
		String saveKey = getSaveKey(upYunSaveFolder, "{random32}{.suffix}");
		HashMap<String, Object> params = new HashMap<String, Object>();
		params.put("return-url", ControllerHelper.getBasePath(request)
				+ "upyun/notify");

		String policy = UpYunUtils.makePolicy(saveKey, expiration,
				uploader.getBucket(), params);
		String signature = getSignature(policy, uploader.getApiKey());
		return new UpYunEntity(uploader.getBucket(), policy, signature);
	}

	@RequestMapping(value = "notify", method = RequestMethod.GET)
	@ResponseBody
	public UeditorCallBackEntity notifyUrl(UpYunCallBackEntity upyunImage,
			WebRequest request) throws Exception {
		return new UeditorCallBackEntity(upyunImage);
	}

	@RequestMapping(value = "imageManager", method = RequestMethod.POST)
	@ResponseBody
	public String imageManager(String upYunSaveFolder) {
		List<FolderItem> list = upYun.readDir(upYunSaveFolder);
		StringBuffer buffer = new StringBuffer();
		for (int i = 0; list != null && i < list.size(); i++) {
			buffer.append("/");
			buffer.append(list.get(i).name);
			buffer.append("ue_separate_ue");
		}
		String imgStr = buffer.toString();

		if (!imgStr.equals("")) {
			imgStr = imgStr.substring(0, imgStr.lastIndexOf("ue_separate_ue"))
					.replace(File.separator, "/").trim();
		}
		// TODO:delete
		// imgStr =
		// "{'state': 'SUCCESS','total': 1,'start': 0, list: [{'state': 'SUCCESS','url': '/1414069380434085459.jpeg'},{'state': 'SUCCESS','url': '/assets/upload/image/20140929/1411969473617067358.jpg'},{'state': 'SUCCESS','url': '/assets/upload/image/20140929/1411969732515052957.jpg'},{'state': 'SUCCESS','url': '/assets/upload/image/20140929/1411975027686024411.jpg'},{'state': 'SUCCESS','url': '/assets/upload/image/20141023/1414058818382082648.jpg'},{'state': 'SUCCESS','url': '/assets/upload/image/20141023/1414069380434085459.jpeg'},{'state': 'SUCCESS','url': '/assets/upload/image/20141024/1414126588130003684.jpeg'} ]}";
		return imgStr;
	}

    /**
     * 上传图片空间获取密匙
     *
     * @param request 请求
     * @param response 响应
     * @return map
     */
    @RequestMapping(value = "bucketapi", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> bucketAndApi(HttpServletRequest request, HttpServletResponse response){
        Map<String, Object> map = new HashMap<>();
        map.put("formId", uploader.getApiKey());
        map.put("bucket", uploader.getBucket());
        map.put("returnUrl", "http://kjc-images.b0.upaiyun.com");
        return map;
    }

    @RequestMapping(value = "bucketapioffile", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> bucketOfFile(HttpServletRequest request, HttpServletResponse response){
        Map<String, Object> map = new HashMap<>();
        map.put("formId", uploaderFile.getApiKey());
        map.put("bucket", uploaderFile.getBucket());
        map.put("returnUrl", "http://kjc-app.b0.upaiyun.com");
        return map;
    }

	public String getSaveKey(String saveFloder, String pattern) {
		return "/" + saveFloder + "/" + pattern;
	}

	public String getSignature(String policy, String API_KEY) {
		return UpYunUtils.signature(policy + "&" + API_KEY);
	}

}
